package org.dsapr.codegen.processor.vo;

import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.TypeSpec;
import lombok.Data;
import org.dsapr.codegen.common.AutoGenerateVo;
import org.dsapr.codegen.common.BaseGenerateProcessor;
import org.dsapr.codegen.common.CodeGenerateProcessor;
import org.dsapr.codegen.model.NameContext;

import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import java.io.File;
import java.lang.annotation.Annotation;
import java.nio.file.Path;
import java.nio.file.Paths;

@AutoService(value = CodeGenerateProcessor.class)
public class VoAutoGenerateProcessor extends BaseGenerateProcessor {
    private static final String CODEGEN_INFO = buildMessage();

    @Override
    public void generateClass(TypeElement typeElement, RoundEnvironment roundEnvironment) throws Exception {
        NameContext context = NameContext.builder().build(typeElement);
        FieldSpec idFiled = FieldSpec
                .builder(ClassName.get(Long.class), "id", Modifier.PRIVATE).build();

        TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(context.getVoClassName())
                .addJavadoc(CODEGEN_INFO)
                .addAnnotation(Data.class)
                .addModifiers(Modifier.PUBLIC)
                .addField(idFiled);

        Path srcPath = Paths.get(typeElement.getAnnotation(AutoGenerateVo.class).sourcePath());
        File srcAbsoluteFile = srcPath.toFile().getAbsoluteFile();
        if (srcAbsoluteFile.exists()) {
            File sourceFile = new File(srcAbsoluteFile.getAbsolutePath(), context.getControllerClassName() + ".java");
            if (!sourceFile.exists()) {
                writeJavaFile(getPackage(typeElement), typeSpecBuilder.build(), srcAbsoluteFile.getAbsolutePath());
            }
        }
    }

    @Override
    public Class<? extends Annotation> getAnnotation() {
        return AutoGenerateVo.class;
    }

    @Override
    public String getPackage(TypeElement typeElement) {
        return typeElement.getAnnotation(AutoGenerateVo.class).packageName();
    }
}
